package com.movie.demo.controller;

import com.movie.demo.pojo.Movie;
import com.movie.demo.Utlis.result.CommonResult;
import com.movie.demo.service.MovieService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;

@RestController
@CrossOrigin
public class MovieController {
    @Autowired
    private MovieService movieService;

    @PostMapping("/Movies")
    public CommonResult<List> selectMovie(){
        List<Movie> movieList = movieService.selectMovie();
        if(movieList!=null){
            return CommonResult.success(movieList);
        }
        return CommonResult.failed();
    }
    @PostMapping("/AddMovie")
    public CommonResult addMovie(@RequestBody Movie movie){
        Boolean flag=movieService.addMovie(movie);
        if (flag){
            return CommonResult.success(flag);
        }
        return CommonResult.failed();
    }
    @PostMapping("/MovieDelete")
    public CommonResult Delete( @RequestBody  Movie movieID){
        boolean result=movieService.deleteMovie(movieID.getMid());
        if (result) {
            return CommonResult.success(result);
        }
        return CommonResult.failed();
    }
    @PostMapping("/UpdateMovie")
    public CommonResult Update(@RequestBody Movie movie){
        boolean result=movieService.updateMovie(movie);
        if (result) {
            return CommonResult.success(result);
        }
        return CommonResult.failed();
    }
    @RequestMapping("/SearchMovie")
    public CommonResult<List> searchMovie(@RequestParam("searchstr") String searchstr){
        List<Movie> movieList = movieService.searchMovie(searchstr);
        return CommonResult.success(movieList);
    }
    @RequestMapping("SearchMovieid")
    public CommonResult<List> searchMovieid(@RequestBody Movie movie){
        List<Movie> movieList = movieService.searchMovieid(movie.getMid());
        return CommonResult.success(movieList);
    }
    @RequestMapping("/TopMovie")
    public CommonResult<List> topMovie(){
        List<Movie> movieList=movieService.topMovie();
        return CommonResult.success(movieList);
    }
    @PostMapping("/Upload")
    public CommonResult upload(@RequestParam("aa") MultipartFile multipartFile) throws IOException, ParseException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (multipartFile !=null){
            System.out.println(multipartFile.getOriginalFilename());
            map.put("filename",multipartFile.getName());
            map.put("contentType", multipartFile.getContentType());
            map.put("fileSize", multipartFile.getSize());
            String filePath = "D:\\IDEAwork\\movie\\src\\main\\resources\\static\\upload\\"+multipartFile.getOriginalFilename();
            // 保存文件的路径信息
           map.put("filePath", filePath);
           // 创建文件
            File saveFile = new File(filePath);
         // 文件保存
           multipartFile.transferTo(saveFile);

        //        1.通过流读取Excel文件
        FileInputStream inputStream = new FileInputStream(filePath);
//        2.通过poi解析流 HSSFWorkbook 处理流得到的对象中 就封装了Excel文件所有的数据
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//        3.从文件中获取表对象  getSheetAt通过下标获取
//        HSSFSheet sheet = workbook.getSheetAt(0);
            XSSFSheet xssfSheet=workbook.getSheetAt(0);
//        4.从表中获取到行数据  从第二行开始 到 最后一行  getLastRowNum() 获取最后一行的下标
        int lastRowNum = xssfSheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
//            通过下标获取行
            XSSFRow row = xssfSheet.getRow(i);
//            从行中获取数据
            /**
             * getNumericCellValue() 获取数字
             * getStringCellValue 获取String
             */
            String chinese_name = row.getCell(0).getStringCellValue();
            String english_name = row.getCell(1).getStringCellValue();
            String img_url=row.getCell(2).getStringCellValue();
            String type=row.getCell(3).getStringCellValue();
            String length=row.getCell(4).getStringCellValue();
            Date release_date= HSSFDateUtil.getJavaDate(row.getCell(5).getNumericCellValue());
            String introduction=row.getCell(6).getStringCellValue();
            String rating= String.valueOf(row.getCell(7).getNumericCellValue());
            String country=row.getCell(8).getStringCellValue();
            String actors=row.getCell(9).getStringCellValue();
            String director=row.getCell(10).getStringCellValue();
            float price= (float) row.getCell(11).getNumericCellValue();

//            封装到对象中
            Movie movie = new Movie();
            movie.setChinese_name(chinese_name);
            movie.setEnglish_name(english_name);
            movie.setImg_url(img_url);
            movie.setType(type);
            movie.setLength(length);
            movie.setRelease_date(release_date);
            movie.setIntroduction(introduction);
            movie.setRating(rating);
            movie.setCountry(country);
            movie.setActors(actors);
            movie.setDirector(director);
            movie.setPrice(price);
//            将对象添加数据库
            System.out.println(movie);
            movieService.addMovie(movie);
        }
        return CommonResult.success(true);
        }
        return CommonResult.failed();
        }
    @PostMapping("/Export")
    public CommonResult exports() throws IOException {
        List<Movie> movieList = movieService.selectMovie();
        String[] titles = {"chinese_name", "english_name", "img_url","type","length","release_date","introduction","rating",
        "country","actors","director","price"};
        /**
         * 先写入 标题栏数据
         */
//        1.创建文件对象   创建HSSFWorkbook只能够写出为xls格式的Excel
//        要写出 xlsx 需要创建为 XSSFWorkbook 两种Api基本使用方式一样
        HSSFWorkbook workbook = new HSSFWorkbook();
//        2.创建表对象
        HSSFSheet sheet = workbook.createSheet("users");
//        3.创建标题栏（第一行）  参数为行下标  行下标从0开始
        HSSFRow titleRow = sheet.createRow(0);
//        4.在标题栏中写入数据
        for (int i = 0; i < titles.length; i++) {
//            创建单元格
            HSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }
        /**
         * 写入用户数据
         */
//       5 创建行 如果是用户数据的集合 需要遍历
        for (int i = 0; i < movieList.size(); i++) {
            HSSFRow row = sheet.createRow(i+1);
//       6 将用户数据写入到行中
            row.createCell(0).setCellValue(movieList.get(i).getChinese_name());
            row.createCell(1).setCellValue(movieList.get(i).getEnglish_name());
            row.createCell(2).setCellValue(movieList.get(i).getImg_url());
            row.createCell(3).setCellValue(movieList.get(i).getType());
            row.createCell(4).setCellValue(movieList.get(i).getLength());
            row.createCell(5).setCellValue(DateFormat.getDateTimeInstance().format(movieList.get(i).getRelease_date()));
            row.createCell(6).setCellValue(movieList.get(i).getIntroduction());
            row.createCell(7).setCellValue(movieList.get(i).getRating());
            row.createCell(8).setCellValue(movieList.get(i).getCountry());
            row.createCell(9).setCellValue(movieList.get(i).getActors());
            row.createCell(10).setCellValue(movieList.get(i).getDirector());
            row.createCell(11).setCellValue(movieList.get(i).getPrice());
        }
//        文件保存到本地 参数为要写出的位置
        workbook.write(new FileOutputStream("D:\\IDEAwork\\movie\\src\\main\\resources\\static\\upload\\Expromovie.xls"));
        return CommonResult.success("1");
    }

    }
